<!-- 表格组件 -->
<script lang="tsx" setup>
import { toRaw } from 'vue';

import type { TableColumnOption } from '@/components/table-widget/table-widget.vue';
import TableWidget from '@/components/table-widget/table-widget.vue';
import {
  ARTICLE_TYPE_OPTIONS,
  getEnumOptionsField,
  SYSTEM_USER_WORKER_TYPE_OPTIONS,
} from '@/config/enum-options';
import { whManagerBsTbArticleDeleteByIdIdUsingPost } from '@/genapi/wh';

import { injectState } from '../state';

defineOptions({ name: 'Sheet' });

const {
  selectedList,
  tableRef,
  detailDialogRef,
  page: { records, isLoading, execute },
} = injectState()!;

watch(records, () => tableRef.value?.table?.clearSelection());

const onDelete = async (row: (typeof records.value)[0]) => {
  await ElMessageBox.confirm(
    `您即将删除【${row.name ?? '未知'}】，删除后不可恢复，是否确认删除？`,
    {
      type: 'error',
      title: '提示',
    },
  );
  await whManagerBsTbArticleDeleteByIdIdUsingPost({ path: { id: row.id! } });
  ElMessage.success('删除成功');
  await execute();
};

const columns: TableColumnOption<(typeof records.value)[0]>[] = [
  {
    type: 'selection',
    fixed: 'left',
    noExport: true,
  },
  {
    label: '序号',
    type: 'index',
    fixed: 'left',
    width: 80,
  },
  {
    label: '文章名称',
    formatter: (row) => row.articleName ?? '-',
  },
  {
    label: '文章类型',
    formatter: (row) => getEnumOptionsField(ARTICLE_TYPE_OPTIONS, 'label', row.articleType) ?? '-',
  },
  {
    label: '工种类型',
    formatter: (row) =>
      getEnumOptionsField(SYSTEM_USER_WORKER_TYPE_OPTIONS, 'label', row.workType) ?? '-',
  },
  {
    label: '封面图片',
    formatter: (row) => row.imageId ?? '-',
  },
  {
    label: '上传时间',
    formatter: (row) => row.uploadTime ?? '-',
  },
  {
    label: '文件名称',
    formatter: (row) => row.articleName ?? '-',
  },
  {
    label: '操作',
    export: false,
    fixed: 'right',
    width: '200',
    noExport: true,
    formatter(row) {
      return (
        <>
          <el-button
            size="small"
            type="primary"
            text
            onClick={() => detailDialogRef.value?.trigger('read', row)}
          >
            详情
          </el-button>
          <el-button
            size="small"
            type="primary"
            text
            onClick={() => detailDialogRef.value?.trigger('write', row)}
          >
            编辑
          </el-button>
          <el-button size="small" type="primary" text onClick={() => onDelete(row)}>
            删除
          </el-button>
        </>
      );
    },
  },
];
</script>

<template>
  <TableWidget
    ref="tableRef"
    v-loading="isLoading"
    :data="records"
    :columns="columns"
    h="100%!"
    @selection-change="(rows:any) => (selectedList = toRaw(rows))"
  />
</template>
